/*
 * Copyright 2018-2019 KunMinX
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain menu_text_color copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wanchuang.hepos.ui.page.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.wanchuang.hepos.BuildConfig;
import com.wanchuang.hepos.bridge.data.repository.WebApis;
import com.wanchuang.hepos.databinding.FragmentLoginBinding;
import com.wanchuang.hepos.ui.MainActivity;
import com.wanchuang.hepos.R;
import com.wanchuang.hepos.bridge.data.bean.UserBean;
import com.wanchuang.hepos.bridge.request.LoginRequestViewModel;
import com.wanchuang.hepos.bridge.state.login.LoginViewModel;
import com.wanchuang.hepos.help.UserHelper;
import com.wanchuang.hepos.ui.base.BaseFragment;
import com.wanchuang.hepos.ui.web.ui.WebViewActivity;


/**
 * Create by KunMinX at 19/10/29
 */
public class LoginFragment extends BaseFragment {

    private FragmentLoginBinding mBinding;

    private LoginViewModel mLoginViewModel;

    private LoginRequestViewModel mLoginRequestViewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLoginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
        mLoginRequestViewModel = ViewModelProviders.of(this).get(LoginRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        mBinding = FragmentLoginBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mBinding.setVm(mLoginViewModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 错误信息的回调
        mLoginRequestViewModel.getErrorString().observe(this, error -> {
            hideProgress();
            showShortToast(error);
        });

        // 成功登陆后获取个人信息
        mLoginRequestViewModel.getLoginLiveData().observe(this, login -> {
            UserBean userBean = new UserBean();
            userBean.setKey(login.getKey());
            userBean.setPush_id(login.getPushId());
            UserHelper.login(userBean);
            mLoginRequestViewModel.getMemberInfo();
        });

        // 获取提交接口的令牌
        mLoginRequestViewModel.getFormToken().observe(this, format -> {
            mLoginRequestViewModel.requestLogin(mLoginViewModel.userName.get(), mLoginViewModel.passWord.get(), format);
        });
        // 判断需要跳转实名认证哪一步
        mLoginRequestViewModel.getMember().observe(this, member -> {
            hideProgress();

            if (member.getMerchantStatus().equals("2")) {
                Intent intent = new Intent(mActivity, MainActivity.class);
                startActivity(intent);
                mActivity.finish();
            } else {
                WebViewActivity.startActivity(mActivity, WebApis.merchantAccess);
            }
        });

//
//        mLoginViewModel.userName.set("17876709197");
//        mLoginViewModel.passWord.set("aa123456");
    }

    public class ClickProxy {
        /**
         * 跳转忘记密码页面
         */
        public void forgetPassword() {
            nav().navigate(R.id.action_loginFragment_to_forgetPasswordFragment);
        }

        /**
         * 跳转注册页面
         */
        public void register() {
            nav().navigate(R.id.action_loginFragment_to_registerFragment);
        }

        /**
         * 登陆方法
         */
        public void login() {
            String account = mLoginViewModel.userName.get();
            if (TextUtils.isEmpty(account)) {
                showShortToast("请输入账号");
                return;
            }
            String pwd = mLoginViewModel.passWord.get();
            if (TextUtils.isEmpty(pwd)) {
                showShortToast("请输入密码");
                return;
            }
            showProgress();
            // 登陆
            mLoginRequestViewModel.get_form_token("index");
        }

        /**
         * 设置密码是否为明文显示
         */
        public void checkBox(boolean isChecked) {
            TransformationMethod method;
            if (isChecked) {
                method = PasswordTransformationMethod.getInstance();
            } else {
                method = HideReturnsTransformationMethod.getInstance();
            }
            mBinding.etLoginPassword.setTransformationMethod(method);
            mBinding.etLoginPassword.setSelection(mBinding.etLoginPassword.getText().length());
        }
    }
}
